/**
 * 
 */
package com.homework.datastructures.exercise2.linkedlist;

/**
 * @author public_enemy
 * 
 */
public class LinkedList<E> {

	Entry<E> firstEntry;

	/**
	 * 
	 * @return number of elements in the linked list
	 */
	public int getCurrentSize() {
		int elementCounter = 0;
		Entry<E> currentEntry = firstEntry;

		do {
			if (currentEntry.next == null) {
				elementCounter++;
			} else {
				elementCounter++;
				currentEntry = currentEntry.next;
			}
		} while (currentEntry.next != null);

		return elementCounter;
	}

	/**
	 * 
	 * @param index
	 *            : position to search
	 * @return element at that index value
	 */
	public E getElementByIndex(int index) {
		int indexCounter = 0;
		Entry<E> searchedElement = firstEntry;
		do {
			if (indexCounter == index - 1) {
				return searchedElement.value;
			} else {
				indexCounter++;
				searchedElement = searchedElement.next;
			}
		} while (indexCounter < index);
		return null;
	}

	/**
	 * 
	 * @param value
	 *            : new value to be inserted
	 */
	public void addElement(E value) {
		Entry<E> nextEntry = new Entry<E>();
		nextEntry.value = value;
		nextEntry.next = firstEntry;
		firstEntry = nextEntry;
	}
	
	/**
	 * Remove last Entry
	 */
	public void removeElement() {
		int lastEntry = getCurrentSize();
		int indexCounter = 0;
		Entry<E> tempElement = firstEntry;

		do {
			if (indexCounter == lastEntry - 2) {
				tempElement.next = null;
			} else {
				indexCounter++;
				tempElement = tempElement.next;
			}
		} while (indexCounter < lastEntry - 1);
	}
}
